package interface_layer;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialBlob;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import database_layer.Common;
import database_layer.UpdateDispatcher;

/**
 * This servlet is part of the chain which eventually uploads a picture
 * of the user to the DB. It is triggered by a particular JSP command, and
 * stores the picture as a BLOB in the DB (using the DB layer of course)
 */
public class PictureUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PictureUpload()
    {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String username = (String) request.getSession().getAttribute("username");
			if (null == username)
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
			}
			else
			{
				try
				{
					String contentType = request.getContentType();
					if (null != contentType)
					{
						InputStream inputContent = null;
						int contentLength = 0;
						List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
					    // Only one item
						for (FileItem item : items)
						{
							if (item.isFormField())
					        {
				            } 
							else
					        {
								inputContent = item.getInputStream();
					            contentLength = (int) item.getSize();
					        }
						}
						ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		
						int nRead;
						byte[] data = new byte[contentLength];
		
						while ((nRead = inputContent.read(data, 0, data.length)) != -1)
						{
							buffer.write(data, 0, nRead);
						}
		
						buffer.flush();
		
						Blob image = new SerialBlob(buffer.toByteArray());
						
						inputContent.close();
						buffer.close();
						
						int returnValue = UpdateDispatcher.updateUserImage(username, image);
						ErrorHandler.parseForErrors(returnValue, response, "userPage.jsp");
					}
				}
				catch (Exception e)
				{
					ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
				}
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}

}
